<template>
    <div class="delivery-section">
        <!-- 地址卡片 -->
        <div class="address-card" @click="goToAddressList">
            <div class="address-info">
                <p class="user-info">
                    {{ userPhone }}
                    <span v-if="userName"> ({{ userName }}) </span>
                </p>
                <p class="address-detail"> {{ addressDetail }} </p>
            </div>
            <van-icon name="arrow" class="arrow-icon" />
        </div>

        <!-- 商品卡片 -->
        <div class="goods-card" v-if="cartItems.length > 0">
            <div class="goods-item" v-for="(item, index) in cartItems" :key="index">
                <img class="goods-img" :src="item.image_url" alt="商品图" v-if="item.image_url" />
                <div class="goods-img placeholder" v-else></div>
                <div class="goods-desc">
                    <p class="goods-name"> {{ item.product_name }} </p>
                    <p class="goods-specs" v-if="item.specs"> 规格：{{ item.specs }} </p>
                    <p class="goods-toppings" v-if="item.toppings"> 小料：{{ item.toppings }} </p>
                    <p class="goods-price"> ¥{{ item.price }} x {{ item.quantity }} </p>
                </div>
            </div>
        </div>
        <van-skeleton title :row="3" v-else />

        <!-- 费用明细 -->
        <div class="fee-card">
            <div class="fee-item">
                <span>商品金额</span>
                <span class="amount"> ¥{{ totalPrice.toFixed(2) }} </span>
            </div>
            <div class="fee-item">
                <span>会员折扣</span>
                <span class="discount"> -¥{{ memberDiscount.toFixed(2) }} </span>
            </div>
            <div class="fee-item">
                <span>配送费</span>
                <span class="amount"> ¥{{ freight.toFixed(2) }} </span>
            </div>
            <div class="fee-item remark-item">
                <span>备注</span>
                <van-field v-model="remark" placeholder="请填写备注信息" class="remark-input" />
            </div>
        </div>

        <!-- 支付方式 -->
        <div class="pay-card">
            <div class="pay-title">选择支付方式</div>
            <van-radio-group v-model="selectedPay">
                <van-radio name="wechat" class="pay-item" checked-color="#ee0a24">
                    <div class="pay-left">
                        <van-icon name="wechat" color="#07c160" size="20" class="pay-icon" />
                        <span class="pay-text">微信</span>
                    </div>
                </van-radio>
                <van-radio name="alipay" class="pay-item" checked-color="#ee0a24">
                    <div class="pay-left">
                        <van-icon name="alipay" color="#1677ff" size="20" class="pay-icon" />
                        <span class="pay-text">支付宝</span>
                    </div>
                </van-radio>
                <van-radio name="balance" class="pay-item" checked-color="#ee0a24">
                    <div class="pay-left">
                        <van-icon name="balance-o" color="#ff976a" size="20" class="pay-icon" />
                        <span class="pay-text">
                            余额
                            <span class="balance-amount"> (可用: ￥{{ balanceAmount.toFixed(2) }}) </span>
                        </span>
                    </div>
                </van-radio>
            </van-radio-group>
            <div class="total-amount">
                实付款 ¥<span class="final-amount"> {{ calculateFinalAmount }} </span>
            </div>
            <van-button round type="danger" class="submit-btn" @click="submitOrder"
                style="float: right; margin-top: 30px;">
                确认订单
            </van-button>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import api from '@/api/history';
import {
    showToast,
    Icon,
    RadioGroup,
    Radio,
    Field,
    Skeleton,
    Button
} from 'vant';

// 路由和参数
const router = useRouter();
const route = useRoute();

// 地址信息
const userName = ref('');
const userPhone = ref('');
const addressDetail = ref('');
const addresses = ref([]);

// 购物车商品
const cartItems = ref([]);
const totalPrice = ref(0);

// 订单信息 - 统一声明，避免重复
const memberDiscount = ref(0.00);
const freight = ref(0.00);
const balanceAmount = ref(9320145.14);
const goodsImage = ref('http://sz4rr0buo.hn-bkt.clouddn.com/%E8%8A%92%E6%9E%9C%E5%A5%B6%E6%98%94.png');
const goodsName = ref('芒果奶昔');
const goodsPrice = ref(0.01);
const goodsCount = ref(1);

const remainingPoints = ref(0);
const pointsDeductionAmount = ref(0);
const usePoints = ref(false);
const usePointsRadio = ref('');
const remark = ref('');
const selectedPay = ref('wechat');
const productIds = ref([]);

onMounted(async () => {
    try {
        // 1. 获取路由传递的商品ID
        const idsFromRoute = route.query.productIds;
        productIds.value = idsFromRoute
            ? idsFromRoute.split(',').map(id => parseInt(id, 10))
            : [];

        // 2. 请求购物车数据（带 Token）
        const cartRes = await api.get('/api/cart/list', {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        });

        if (cartRes.data?.code === 200 && Array.isArray(cartRes.data.data.items)) {
            const validItems = cartRes.data.data.items.filter(item =>
                item.product_id && item.price && item.quantity
            );
            cartItems.value = validItems;
            totalPrice.value = validItems.reduce(
                (sum, item) => sum + Number(item.price) * item.quantity,
                0
            );
        } else {
            console.error('购物车接口返回异常', cartRes.data);
            showToast('购物车数据加载失败');
        }

        // 3. 请求地址数据（带 Token）
        const addressRes = await api.get('/getaddress', {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        });

        if (addressRes.data?.code === 200 && Array.isArray(addressRes.data.data)) {
            addresses.value = addressRes.data.data;
            const defaultAddr = addressRes.data.data.find(addr => addr.is_default)
                || addressRes.data.data[0];

            if (defaultAddr) {
                userName.value = defaultAddr.name;
                userPhone.value = defaultAddr.phone;
                addressDetail.value = defaultAddr.address;
            } else {
                showToast('请添加收货地址');
            }
        } else {
            console.error('地址接口返回异常', addressRes.data);
            showToast('地址数据加载失败');
        }

    } catch (error) {
        console.error('页面初始化失败', error);
        showToast('数据加载失败，请重试');
    }
});

// 计算最终金额
const calculateFinalAmount = computed(() => {
    let total = totalPrice.value;
    total -= memberDiscount.value;
    total += freight.value;
    return Math.max(0, total).toFixed(2);
});

// 跳转地址列表
const goToAddressList = () => {
    router.push('/location');
};

// 提交订单 - 修复嵌套定义问题
const submitOrder = async () => {
    try {
        if (cartItems.value.length === 0) {
            showToast('购物车为空，无法提交订单');
            return;
        }
        if (!addressDetail.value) {
            showToast('请选择收货地址');
            return;
        }

        const userId = localStorage.getItem('userId') || 1;
        const orderData = {
            user_id: parseInt(userId),
            address: addressDetail.value,
            payment_method: selectedPay.value,
            remark: remark.value,
            items: cartItems.value.map(item => ({
                product_id: item.product_id,
                quantity: item.quantity,
                price: item.price,
                specs: item.specs || '',
                toppings: item.toppings || ''
            })),
            total_amount: parseFloat(calculateFinalAmount.value),
            discount_amount: memberDiscount.value,
            freight: freight.value
        };

        const res = await api.post('/api/order/create', orderData, {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        });

        if (res.data.code === 200) {
            showToast('订单提交成功');
            router.push('/order/detail/40'); // 需根据实际订单ID调整
        } else {
            showToast(res.data.message || '订单提交失败');
        }

    } catch (error) {
        console.error('提交订单失败', error);
        showToast('提交订单失败，请重试');
    }
};
</script>

<style scoped>
.delivery-section {
    padding: 16px;
    background-color: #f7f7f7;
    min-height: 100vh;
}

/* 地址卡片 */
.address-card {
    background: #fff;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.user-info {
    font-size: 16px;
    font-weight: 500;
    color: #333;
    margin-bottom: 4px;
}

.address-detail {
    font-size: 14px;
    color: #666;
    line-height: 1.5;
}

.arrow-icon {
    color: #999;
    font-size: 20px;
}

/* 商品卡片 */
.goods-card {
    background: #fff;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.goods-item {
    display: flex;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid #f5f5f5;
}

.goods-item:last-child {
    border-bottom: none;
}

.goods-img {
    width: 80px;
    height: 80px;
    object-fit: cover;
    border-radius: 4px;
    margin-right: 12px;
    background-color: #f5f5f5;
}

.placeholder {
    width: 80px;
    height: 80px;
    background: #f5f5f5;
    border-radius: 4px;
    margin-right: 12px;
}

.goods-desc {
    flex: 1;
}

.goods-name {
    font-size: 14px;
    color: #333;
    margin-bottom: 4px;
    line-height: 1.4;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
    display: -webkit-box;
}

.goods-specs,
.goods-toppings {
    font-size: 12px;
    color: #999;
    margin-bottom: 4px;
}

.goods-price {
    font-size: 14px;
    color: #ee0a24;
    margin-top: 8px;
    font-weight: 500;
}

/* 费用明细 */
.fee-card {
    background: #fff;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.fee-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #f5f5f5;
}

.fee-item:last-child {
    border-bottom: none;
}

.fee-item span {
    font-size: 14px;
}

.amount {
    color: #333;
}

.discount {
    color: #ee0a24;
}

.remark-item {
    align-items: flex-start;
    padding-top: 12px;
}

.remark-input {
    width: 100%;
    margin-top: -4px;
}

/* 支付方式 */
.pay-card {
    background: #fff;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 80px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.pay-title {
    font-size: 14px;
    color: #999;
    margin-bottom: 12px;
}

.pay-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 14px 0;
    border-bottom: 1px solid #f5f5f5;
}

.pay-item:last-child {
    border-bottom: none;
}

.pay-left {
    display: flex;
    align-items: center;
}

.pay-icon {
    margin-right: 10px;
}

.pay-text {
    font-size: 14px;
    color: #333;
}

.balance-amount {
    color: #ee0a24;
    margin-left: 4px;
    font-size: 13px;
}

.total-amount {
    font-size: 14px;
    color: #333;
    margin-top: 20px;
    text-align: right;
    padding: 10px 0;
    border-top: 1px dashed #f5f5f5;
}

.final-amount {
    color: #ee0a24;
    font-size: 18px;
    font-weight: 700;
}

.submit-btn {
    width: 140px;
    height: 45px;
    line-height: 45px;
    padding: 0;
    font-size: 16px;
    font-weight: 500;
}
</style>